﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microhard.JHWorkflowTrans;
using Microhard.WarehouseInsp.Buz.Models;
using Microhard.Core.DBUtility;
using Microhard.Core.Security;
using System.Web;
using Microhard.Core;
using Microhard.WarehouseInsp.Buz.DataAccess;
using Microhard.WarehouseInsp.Buz.BuzEnum;
using Microhard.WarehouseInsp.Buz.DTO;

namespace Microhard.WarehouseInsp.Buz.JHWorkflow
{
    public class SupProjectTransJDImpl : ITransDataInDJ
    {
        public ExecutedResult SaveToDJ(string mainID, Guid pkid, string currentUserLoginCode)
        {
            ExecutedResult result = new ExecutedResult();
            C6Entities db = new C6Entities();
            WarehouseInspEntities wdb = new WarehouseInspEntities();

            #region 添加项目主信息
            var entity = wdb.SupProjects.SingleOrDefault(p => p.ProjectID == pkid);
            if (entity == null)
            {
                result.ErrorMsg.Add("SupProjectTransJDImpl", "添加项目数据到表单失败，无法获取项目信息，PKID:" + pkid);
            }
            SupProjectModel buz = entity.ToModel();
            db.MH_SupProjectApply.AddObject(new MH_SupProjectApply
            {
                MainID = mainID,
                //申请人
                SQR = buz.ApplierName,
                //申请人编号
                SQRBH = buz.ApplierID,
                //授信金额
                SXJE = buz.Credit.ToString(),
                //开始时间
                XMJSSJ = buz.PrjStartTime.ToString(),
                //结束时间
                XMKSSJ = buz.PrjStartTime.ToString(),
                //项目名称
                XMMC = buz.Name,
                //质权人
                ZQR = buz.PedgeeCompanyName,
                //质权人联系人
                ZQRLXR = buz.PedgeeContactor,
                //质权人联系人联系方式
                ZQRLXRDH = buz.PedgeeContactorPhone,
                //仓库租金
                CKZJ = buz.Rent.ToString(),
                //财产保险费
                CZBXF = buz.ProtyInsuranceCharge.ToString(),
                //监管费
                JGF = buz.SupervisionFee.ToString(),
                //监管责任保险费
                JGZRBXF = buz.SupInsuranceCharge.ToString(),
                //借款人
                JKR = buz.BorrowerName,
                //出质人
                CZR = buz.MortgagorName,
                //履约保证金
                LYBZJ = buz.Guarantee.ToString()
            });
            #endregion

            #region 添加附件信息
            var files = wdb.Attachments.Where(a => a.MainDataID == buz.ProjectID).ToList();
            if (files.Count > 0)
            {
                var url = System.Configuration.ConfigurationManager.AppSettings["OtherSysDownloadUrl"];
                var encKey = System.Configuration.ConfigurationManager.AppSettings["SSOKey"];
                foreach (var f in files)
                {
                    MH_Files newfile = new MH_Files
                    {
                        CreateTime = DateTime.Now,
                        FileName = f.Name,
                        FileUrl = url + "?key=" + HttpUtility.UrlEncode(EncDec.Encrypt(currentUserLoginCode, encKey))
                        + "&fileID=" + HttpUtility.UrlEncode(f.AttachmentID.ToString()),
                        MainID = mainID
                    };
                    db.MH_Files.AddObject(newfile);
                }
            }
            #endregion

            #region 添加预警信息
            var supervisions = wdb.SupervisionDetails.Where(s => s.ProjectID == buz.ProjectID).ToList();
            if (supervisions.Count > 0)
            {
                foreach (var s in supervisions)
                {
                    MH_PrjSupDetail detail = new MH_PrjSupDetail
                    {
                        CJSJ = DateTime.Now,
                        GZ = s.Worth.ToString(),
                        JJX = s.Guardline.ToString(),
                        MainID = mainID,
                        YJX = s.WarnAmount.ToString(),
                        ZT = s.Status.ToString()
                    };
                    db.MH_PrjSupDetail.AddObject(detail);
                }
            }
            #endregion

            #region 添加质押物信息
            var pledges = wdb.PledgePlanInRecords.Where(p => p.ProjectID == buz.ProjectID).ToList();
            if (pledges.Count > 0)
            {
                foreach (var p in pledges)
                {
                    MH_PlgPrdList pp = new MH_PlgPrdList
                    {
                        CK = p.Warehouse.Name,
                        DJ = p.PlanPrice.ToString(),
                        HJ = p.PlanAmount.ToString(),
                        MainID = mainID,
                        MC = p.ProductList.Name,
                        SL = p.PlanCount.ToString()
                    };
                    db.MH_PlgPrdList.AddObject(pp);
                }
            }
            #endregion

            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error("SupProjectTransJDImpl.SaveToDJ", ex);
            }
            return result;
        }


        public void UpdateBuzDataStatus(Guid buzmainID, List<ApproveInfo> approveInfo, bool approvedStatus)
        {
            if (approveInfo == null)
            {
                Log.Error("UpdateBuzDataStatus", "ProjectID:" + buzmainID + "无法获取审批信息");
                return;
            }
            //获取业务数据
            WarehouseInspEntities db = new WarehouseInspEntities();
            var entity = db.SupProjects.SingleOrDefault(w => w.ProjectID == buzmainID);
            if (entity == null)
            {
                Log.Error("UpdateBuzDataStatus", "ProjectID:" + buzmainID + "获取实体失败");
                return;
            }
            //更新审批信息
            if (approvedStatus)
            {
                entity.Status = (int)PrjStatus.Finished;
            }
            else
            {
                entity.Status = (int)PrjStatus.RollBack;
            }
            //更新预警明细审批状态
            var sups = entity.SupervisionDetails.Where(w => w.Status == (int)PrjStatus.Approving);
            foreach (var s in sups)
            {
                s.Status = entity.Status;
            }
            //更新质押物明细审批状态
            var plgs = entity.PledgePlanInRecords.Where(w => w.Status == (int)PrjStatus.Approving);
            foreach (var p in plgs)
            {
                p.Status = entity.Status;
            }
            //保存审批意见
            foreach (var a in approveInfo)
            {
                ApproveRecord ar = new ApproveRecord
                {
                    ApproveEndTime = a.ApproveEndTime,
                    ApproverName = a.ApproverName,
                    CreateTime = DateTime.Now,
                    Info = a.Info,
                    IsPass = a.IsPass,
                    PKID = buzmainID
                };
                db.ApproveRecords.AddObject(ar);
            }
            try
            {
                db.SaveChanges();
            }
            catch (Exception ex)
            {
                Log.Error("UpdateBuzDataStatus", ex);
            }
        }


        public string WorkflowCode
        {
            get { return "SupPrjApply"; }
        }
    }
}
